<template>
    <div class="app-container">
        <div class="container">
            <!-- 商品规格 -->
            <el-form
                v-loading="loading"
                ref="form"
                class="myfrom"
                :model="form"
                label-width="120px"
            >
                <el-form-item label="商品标题" style="width: 100%">
                    <el-input
                        v-model="form.title"
                        :readonly="isReadonly"
                        placeholder="请输入商品标题"
                    ></el-input>
                </el-form-item>
                <el-form-item label="商品分类">
                    <el-cascader
                        :disabled="isReadonly"
                        style="width: 100%"
                        v-model="form.cate_id"
                        :options="classList"
                        placeholder="请选择商品分类"
                        :props="{
                            emitPath: false,
                            expandTrigger: 'hover',
                            children: 'child',
                            value: 'id',
                            label: 'title',
                        }"
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="库存预警值" style="width: 100%">
                    <el-input
                        v-model="form.stock_warning"
                        :readonly="isReadonly"
                        placeholder="请输入库存预警值"
                    ></el-input>
                </el-form-item>
                <el-form-item label="实体卡券" style="width: 100%">
                    <el-radio-group :disabled="form.is_frequency==1" v-model="form.is_entity">
                        <el-radio :label="1" :disabled="isReadonly">是</el-radio>
                        <el-radio :label="0" :disabled="isReadonly">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="次卡" style="width: 100%">
                    <el-radio-group :disabled="form.is_entity==1" v-model="form.is_frequency">
                        <el-radio :label="1" :disabled="isReadonly">是</el-radio>
                        <el-radio :label="0" :disabled="isReadonly">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品轮播图" style="width: 100%">
                    <vs-uploading
                        v-model="form.picture"
                        :readonly="isReadonly"
                        :maxNum="5"
                    ></vs-uploading>
                </el-form-item>
                <el-form-item label="商品简介">
                    <div ref="edit"></div>
                </el-form-item>
                <!-- 商品规格 -->
                <el-form-item label="商品规格" style="width: 100%">
                    <template v-if="!isonr">
                        <el-button
                            v-if="!isReadonly "
                            type="primary"
                            size="medium "
                            @click="specShow = true"
                            >新增</el-button
                        >
                    </template>
                </el-form-item>
                <el-form-item label="" style="width: 100%">
                    <el-table
                        ref="multipleTable"
                        :data="list"
                        tooltip-effect="dark"
                        :header-cell-style="{ background: '#f5f6f8' }"
                    >
                        <el-table-column prop="name" label="规格" min-width="100">
                        </el-table-column>
                        <el-table-column label="规格值">
                            <template slot-scope="scope">
                                <el-checkbox-group
                                    :disabled="isReadonly||isonr"
                                    @change="checkboxSku"
                                    v-model="checkList[scope.$index].list"
                                >
                                    <el-checkbox
                                        v-for="(item, index) in scope.row.list"
                                        :label="item"
                                        :key="index"
                                    ></el-checkbox>
                                </el-checkbox-group>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            v-if="!isReadonly "
                            width="230"
                        >
                            <template v-if="!isonr" slot-scope="scope">
                                <div>
                                    <span
                                        class="tab-table-text"
                                        @click="setSku(scope)"
                                        >编辑</span
                                    >
                                    <span
                                        class="tab-red-text"
                                        @click="delSku(scope.$index)"
                                        >删除</span
                                    >
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <el-form-item label="价格&库存"></el-form-item>
                <el-form-item>
                    <el-form-item>
                        <el-table
                            ref="multipleTable"
                            :data="tableData"
                            size="mini"
                            tooltip-effect="dark"
                            border
                            :header-cell-style="{ background: '#f5f6f8' }"
                        >
                            <el-table-column
                                v-for="(ele, index) in skrList"
                                :key="index"
                                :label="ele"
                                :prop="ele"
                            >
                                <template slot-scope="scope">
                                    {{ scope.row[ele] }}
                                </template>
                            </el-table-column>
                            <el-table-column label="销售价">
                                <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.sale_price"
                                        size="small"
                                        placeholder="销售价"
                                        type="number"
                                        :readonly="isReadonly"
                                        :min="0"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="会员价">
                                <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.vip_price"
                                        size="small"
                                        placeholder="会员价"
                                        type="number"
                                        :readonly="isReadonly"
                                        :min="0"
                                    ></el-input>
                                </template>
                            </el-table-column>
                            <!-- <el-table-column label="积分价">
                                <template slot-scope="scope">
                                    <el-input
                                        v-model="scope.row.integral_price"
                                        size="small"
                                        placeholder="积分价"
                                        type="number"
                                        :readonly="isReadonly"
                                        :min="0"
                                    ></el-input>
                                </template>
                            </el-table-column> -->
                            <!-- <el-table-column label="库存">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.stock"
                    size="small"
                    placeholder="库存"
                    type="number"
                    :readonly="isReadonly"
                    :min="0"
                  ></el-input>
                </template>
              </el-table-column> -->
                            <el-table-column label="图片">
                                <template slot-scope="scope">
                                    <div class="flex-center">
                                        <!-- {{scope.row.img}} -->
                                        <vs-uploading
                                            width="80px"
                                            :readonly="isReadonly"
                                            v-model="scope.row.img"
                                        ></vs-uploading>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-form-item>
                <el-form-item>
                    <el-button
                        v-if="!isReadonly"
                        type="primary"
                        :loading="isBtn"
                        @click="onSubmit"
                        >提交</el-button
                    >
                    <el-button @click="utils.backPage()">取消</el-button>
                </el-form-item>
            </el-form>
            <!-- {{checkList}} @ {{list}} -->
        </div>

        <el-dialog
            v-if="!isReadonly"
            title="规格属性"
            :visible.sync="specShow"
            :close-on-click-modal="false"
            :before-close="closeSku"
            width="500px"
        >
            <el-form ref="form" :model="spec" label-width="80px" class="myfrom">
                <el-form-item prop="specName" label="规格名">
                    <el-input
                        v-model.trim="spec.specName"
                        placeholder="请输入规格名称"
                        style="width: 300px"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="specVal" label="规格值">
                    <el-input
                        @keyup.enter.native="addSpecVal"
                        v-model.trim="spec.specVal"
                        placeholder="请输入规格值(回复快速输入)"
                        style="width: 300px"
                    ></el-input>
                    <el-button
                        type="success"
                        style="margin-left: 10px"
                        @click="addSpecVal"
                        >新增</el-button
                    >
                </el-form-item>
                <div class="sku-value">
                    <el-tag
                        v-for="(tag, index) in spec.tags"
                        :key="index"
                        closable
                        type="success"
                        style="margin-right: 5px"
                        @close="spec.tags.splice(spec.tags.indexOf(tag), 1)"
                    >
                        {{ tag }}
                    </el-tag>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeSku()">取消</el-button>
                <el-button type="primary" @click="addSpecList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import E from "wangeditor";
import VsUploading from "@/components/VsUploading.vue";
export default {
    components: { VsUploading },
    data() {
        return {
            specShow: false,
            list: [
                // { name: "尺码", list: ["S", "M", "L", "XL", "XXL"] },
                // { name: "颜色", list: ["红色", "黄色", "蓝色", "粉色", "紫色"] },
                // { name: "图案", list: ["猫咪", "人物", "飞机", "闪电", "字母"] },
            ],
            hadeList: ["售价",'积分价', "会员价", "库存", "图片"],
            checkList: [
                // { name: "尺码", list: [] },
                // { name: "颜色", list: [] },
                // { name: "图案", list: [] },
            ],
            skrList: [],
            skuArray: [],
            tableData: [],
            spec: {
                specName: "",
                specVal: "",
                tags: [],
            },
            editor: "",
            classList: [],
            loading: false,
            isBtn: false,
            isReadonly: false,
            sku: {
                sku_text: "", //sku组
                sku_id:'',
                stock:'',//库存
                img: "", //图片
                sale_price: "", //销售价
                vip_price: "", //会员价
                integral_price: 0, //积分价
            },
            cloneData: [],
            isonr:false,
            form: {
                is_entity:0,
                is_frequency:0,
                store_id: undefined,
                title: "", //标题
                details: "", //产品简介
                attr: "", //属性/值
                spec: [], //sku
                picture: [], //多图轮播
                cate_id: "", //产品分类id
                stock_warning: "", //库存预警值
            },
        };
    },
    created() {
        this.getGoodsCategory();
        let { id, title, store_id ,isonr} = this.$route.query;
        this.$route.meta.title = title;
        if (title == "详情") {
            this.isReadonly = true;
        }
        if(isonr)this.isonr = true;
        if (store_id) this.form.store_id = store_id;
        if (id) {
            this.getGoods(id);
        } else {
            this.$nextTick(() => {
                this.getEdit();
            });
        }
    },
    mounted() {},
    methods: {
        async getGoods(id) {
            this.loading = true;
            let { code, data } = await this.$Http.getGoods({ id });
            this.loading = false;
            if (code) {
                let {
                        title,
                        picture,
                        details,
                        attr,
                        sku,
                        cate_id,
                        stock_warning,
                        id,
                        store_id,
                        is_entity,
                        is_frequency
                    } = data,
                    activeArr = [];
                attr.forEach((v) => {
                    // console.log(v.val.map(v=>v.attr_value));
                    let arr = {
                        name: v.name,
                        list: v.val.map((v) => v.attr_value),
                    };
                    this.list.push(arr);
                    activeArr.push({
                        name: v.name,
                        list: [],
                    });
                });
                console.log(activeArr, "activeArr");
                sku.forEach((v) => {
                    let skuArr = v.sku_text.split(";"),
                        obj = {
                            sku_id: v.id,
                            sku_text: v.sku_text,
                            stock:v.stock,
                            sale_price: v.sale_price,
                            img: v.img,
                            vip_price: v.vip_price,
                            integral_price: 0,
                        };
                    for (let val of skuArr) {
                        if (val) {
                            let ls = val.split(":");
                            obj[ls[0]] = ls[1];
                            let ins = activeArr.findIndex(
                                (v) => v.name == ls[0]
                            );
                            if (ins != -1) {
                                if (
                                    !activeArr[ins].list.some((v) => v == ls[1])
                                ) {
                                    activeArr[ins].list.push(ls[1]);
                                }
                            }
                        }
                    }
                    this.tableData.push(obj);
                });
                // console.log(activeArr,"activeArractiveArr");
                this.checkList = activeArr;
                this.form = {
                    title,
                    is_entity,
                    is_frequency,
                    store_id,
                    details,
                    picture: picture.split(","),
                    cate_id,
                    stock_warning,
                    attr: "",
                    spec: [], //sku
                    id,
                };
                this.checkList.forEach((v) => {
                    if (v.list.length) {
                        this.skrList.push(v.name);
                    }
                });
                this.cloneData = this.tableData;
                this.$nextTick(() => {
                    this.getEdit();
                });
            }
        },
        async onSubmit() {
            let {
                id,
                title,
                details,
                attr,
                picture,
                spec,
                cate_id,
                stock_warning,
                store_id,
                is_entity,
                is_frequency
            } = JSON.parse(JSON.stringify(this.form));
            // console.log(cate_id,'cate_id');
            if (!title) {
                return this.$message.error("商品标题不能为空!");
            }
            if (!is_entity&&is_entity!=0) {
                return this.$message.error("请选择实体卡!");
            }
            if (!is_frequency&&is_frequency!=0) {
                return this.$message.error("请选择次卡!");
            }
            if (!cate_id) {
                return this.$message.error("商品分类不能为空!");
            }
            if (!stock_warning) {
                return this.$message.error("库存预警值不能为空!");
            }
            if (!picture.length) {
                return this.$message.error("商品轮播图不能为空!");
            }
            if (!details) {
                return this.$message.error("商品简介不能为空!");
            }
            let bol = this.tableData.some((v) => {
                console.log(this.sku,'this.sku',v);
                let obj = {};
                for (let key in this.sku) {
                    obj[key] = v[key];
                    if(key=='sku_id'||key=='stock')continue ;
                    if (!v[key]) return true;
                }
                spec.push(obj);
                return false;
            });
            console.log(bol,!this.tableData.length,this.tableData.length,"!this.tableData.length")
            if (bol || !this.tableData.length) {
                return this.$message.error("规格内容不能为空!");
            }
            picture = picture.join(",");
            attr = JSON.stringify(this.list);
            console.log(spec,'specspecspecspecspecspecspecspec');
            spec = JSON.stringify(spec);
            // return;
            this.isBtn = true;
            let { code, data } = await this.$Http.setGoods({
                id,
                title,
                details,
                attr,
                picture,
                spec,
                cate_id,
                stock_warning,
                store_id,
                is_entity,
                is_frequency
            });
            this.isBtn = false;
            if (code) {
                this.$message.success(id ? "修改成功" : "添加成功");
                this.utils.backPage();
            }
        },
        async getGoodsCategory() {
            let { code, data } = await this.$Http.getGoodsCategory({
                limit: 10000,
            });
            if (code) {
                data.data.forEach((v) => {
                    if (!v.child.length) delete v.child;
                });
                this.classList = data.data;
                // console.log(this.classList,'this.classList');
            }
        },
        // 富文本编辑
        getEdit() {
            this.editor = new E(this.$refs.edit);
            this.editor.config.onchange = (html) => {
                this.form.details = html;
            };
            this.editor.config.customUploadImg = (resultFiles, insertImgFn) => {
                let formData = new window.FormData();
                formData.append("files", resultFiles[0]);
                this.$Http.upload(formData).then((res) => {
                    if (res.status) {
                        this.$message({
                            message: "上传成功",
                            type: "success",
                        });
                        insertImgFn(res.data);
                    }
                });
            };
            this.editor.config.customUploadVideo = (
                resultFiles,
                insertVideoFn
            ) => {
                let formData = new window.FormData();
                formData.append("files", resultFiles[0]);
                this.$Http.upload(formData).then((res) => {
                    if (res.status) {
                        this.$message({
                            message: "上传成功",
                            type: "success",
                        });
                        insertVideoFn(res.data);
                    }
                });
            };
            this.editor.create();
            this.editor.txt.html(this.form.details);
            // console.log("禁用");
            if (this.isReadonly) {
                this.editor.disable();
                this.editor.$textElem.attr("contenteditable", false); //设置不可编辑
            }
            this.editor.$textContainerElem.css("height", "600px !important"); //设置高度
        },
        getSkuData(skuArr = [], i, list) {
            for (let j = 0; j < list[i].length; j++) {
                if (i < list.length - 1) {
                    skuArr[i] = list[i][j];
                    this.getSkuData(skuArr, i + 1, list); // 递归循环
                } else {
                    let obj = {},
                        arr = [...skuArr, list[i][j]],
                        sku_text = [];
                    this.skrList.forEach((v, i) => {
                        obj[v] = arr[i];
                    });
                    for (let val in obj) {
                        sku_text.push(`${val}:${obj[val]}`);
                    }
                    sku_text = sku_text.join(";");
                    let vsd = this.cloneData.find(
                        (v) => v.sku_text == sku_text
                    );
                    if (vsd) {
                        this.tableData.push({
                            ...obj,
                            ...vsd,
                        });
                    } else
                        this.tableData.push({
                            ...obj,
                            sku_text, //sku组
                            sku_id: "",
                            //    stock:'',//库存
                            img: "", //图片
                            sale_price: "", //销售价
                            vip_price: "", //会员价
                            integral_price: 0, //积分价
                        }); // 扩展运算符，连接两个数组
                }
            }
        },
        checkboxSku() {
            console.log("更新");
            this.skrList = [];

            this.tableData = [];
            this.checkList.forEach((v) => {
                if (v.list.length) {
                    this.skrList.push(v.name);
                }
            });
            this.skuArray = [];
            // 将选中的规格组合成一个大数组
            this.checkList.forEach((element) => {
                element.list.length > 0 ? this.skuArray.push(element.list) : "";
            });
            // 勾选了规格，才调用方法
            if (this.skuArray.length > 0) {
                this.getSkuData([], 0, this.skuArray);
            }
        },
        delSku(index) {
            //删除规格
            this.list.splice(index, 1);
            this.checkList.splice(index, 1);
            this.checkboxSku()
        },
        setSku(scope) {
            //修改规格
            let row = JSON.parse(JSON.stringify(scope.row));
            this.specShow = true;
            this.spec = {
                index: scope.$index,
                specName: row.name,
                tags: row.list,
            };
        },
        //规格弹框关闭回调
        closeSku(dom) {
            this.specShow = false;
            console.log(this.list, "@@@@");
            dom && dom();
            this.spec = this.$options.data().spec;
            this.checkboxSku();
        },
        //新增规格值列表
        addSpecVal() {
            if (!this.spec.specName) {
                this.$message.warning("请输入规格名");
                return;
            }
            if (!this.spec.specVal) return;
            if (this.spec.tags.indexOf(this.spec.specVal) == -1) {
                this.spec.tags.unshift(this.spec.specVal);
                this.spec.specVal = "";
            } else this.$message.warning("该规格值已存在");
        },
        addSpecList() {
            if (!this.spec.specName) {
                this.$message.warning("请输入规格名");
                return;
            }
            if (!this.spec.tags.length) {
                this.$message.warning("至少输入一个规格值");
                return;
            }
            if ("index" in this.spec) {
                this.list.splice(this.spec.index, 1, {
                    name: this.spec.specName,
                    list: this.spec.tags,
                });
                //    this.checkList.splice(,1,{ name: , list: [] });
                // this.checkList[this.spec.index].name = this.spec.specName;
                // this.checkList[this.spec.index].name = [];
                // this.checkList[this.spec.index].name = {
                //     name: this.spec.specName,
                //     list: [],
                // } 
                this.checkList.splice(this.spec.index,1,{ name: this.spec.specName, list: [] });
                // this.$forceUpdate();
                this.checkboxSku();
            } else if ( this.checkList.find((v) => v.name == this.spec.specName)) {
                return this.$message.error('规格名重复!')
            } else {
                this.list.push({
                    name: this.spec.specName,
                    list: this.spec.tags,
                });
                this.checkList.push({ name: this.spec.specName, list: [] });
            }
            //   if (this.title == "新增") {
            //     this.list.push({ name: this.spec.specName, list: this.spec.tags });
            //     this.checkList.push({ name: this.spec.specName, list: [] });
            //   } else {
            //     this.list[this.specIndex].name = this.spec.specName;
            //     this.list[this.specIndex].list = this.spec.tags;
            //   }
            this.closeSku();
        },
        addPriceBtn() {},
    },
};
</script>

<style lang="scss" scoped>
::v-deep {
    .w-e-toolbar {
        z-index: auto !important;
    }
    .w-e-menu {
        z-index: 2 !important;
    }
    .w-e-text-container {
        z-index: 1 !important;
    }
}

.container {
    width: 100%;
    background: #fff;
    border-radius: 8px;
    padding: 20px;
}
.sku-value {
    user-select: none;
    span {
        margin-top: 5px;
    }
}
</style>